<template>
  <view class="explore-page bg-white h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <view class="px-4 pt-12 pb-2">
      <text class="text-xl font-bold">图案广场</text>
    </view>

    <!-- 分类标签 - 水平排列固定在顶部 -->
    <view class="category-container sticky">
      <scroll-view 
        scroll-x="true" 
        class="category-scroll" 
        show-scrollbar="false"
        enhanced="true"
      >
        <view class="category-row">
          <view 
            v-for="category in categories" 
            :key="category.value"
            class="category-item"
            :class="selectedCategory === category.value ? 'category-active' : ''"
            @click="selectCategory(category.value)"
          >
            <text class="category-text">{{ category.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 主要内容区域 -->
    <scroll-view 
      class="flex-1 px-2 pt-2 pb-4 overflow-auto" 
      scroll-y="true" 
      @scrolltolower="loadMorePatterns"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 热门播放列表 - 不受分类影响，始终显示 -->
      <view class="mb-6 mt-3">
        <view class="flex items-center justify-between mb-3 px-1">
          <text class="text-xl font-bold">热门播放列表</text>
        </view>
        
        <view class="featured-playlist-container">
          <view 
            v-for="(playlist, index) in featuredPlaylists" 
            :key="index"
            class="featured-playlist overflow-hidden relative"
            @click="goToPlaylist(playlist.id)"
          >
            <view class="playlist-card-content" :style="{ background: playlist.background }">
              <view class="absolute inset-0 p-4 flex flex-col justify-between">
                <view class="text-content ml-3 mt-2">
                  <text class="text-white text-lg font-bold block mb-1">{{ playlist.title }}</text>
                  <text class="text-white text-xs opacity-90 block">{{ playlist.count }}个图案</text>
                </view>
                <view class="flex justify-end">
                  <view class="play-btn-circle">
                    <text class="fas fa-play text-white play-icon"></text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 图案列表标题 -->
      <view class="my-4">
        <view class="flex items-center justify-between">
          <text class="text-lg font-bold">
            <!-- 根据不同类别显示不同标题 -->
            <template v-if="selectedCategory === 'all'">热门推荐</template>
            <template v-else>{{ categories.find(c => c.value === selectedCategory)?.name || '全部图案' }}</template>
            <text class="text-sm text-gray-500 ml-2">({{ totalCount }})</text>
          </text>
          <view class="flex items-center space-x-2">
            <picker 
              :range="sortOptions" 
              range-key="name"
              :value="sortIndex"
              @change="onSortChange"
              class="text-sm text-blue-500"
            >
              <text class="text-sm text-blue-500">{{ sortOptions[sortIndex].name }}</text>
            </picker>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading && patterns.length === 0" class="flex justify-center items-center py-20">
        <text class="text-gray-500">加载中...</text>
      </view>

      <!-- 热门推荐 + 图案网格合并 -->
      <view v-else-if="patterns.length > 0 || (selectedCategory === 'all' && featuredPatterns.length > 0)" class="grid grid-cols-2 gap-4 pb-20">
        <!-- 热门推荐部分 -->
        <template v-if="selectedCategory === 'all' && featuredPatterns.length > 0">
          <view 
            v-for="pattern in featuredPatterns"
            :key="pattern._id"
            class="overflow-hidden shadow-sm border border-gray-200 rounded-lg"
            @click="goToPatternDetail(pattern._id)"
          >
            <view class="block">
              <view class="aspect-square bg-gray-100 flex items-center justify-center pattern-image-wrapper">
                <image 
                  :src="pattern.preview_image || pattern.thumbnail || '/static/pattern_images/default.svg'"
                  class="w-full h-full object-cover pattern-image"
                  mode="aspectFill"
                  @error="handleImageError"
                />
              </view>
              <view class="p-3">
                <text class="font-medium text-gray-900">{{ pattern.pattern_name }}</text>
              </view>
            </view>
          </view>
        </template>
        
        <!-- 普通图案列表 -->
        <view 
          v-for="pattern in patterns"
          :key="pattern._id"
          class="overflow-hidden shadow-sm border border-gray-200 rounded-lg"
          @click="goToPatternDetail(pattern._id)"
        >
          <view class="block">
            <view class="aspect-square bg-gray-100 flex items-center justify-center pattern-image-wrapper">
              <image 
                :src="pattern.preview_image || pattern.thumbnail || pattern.pattern_file || '/static/pattern_images/default.svg'"
                class="w-full h-full object-cover pattern-image"
                mode="aspectFill"
                @error="handleImageError"
              />
            </view>
            <view class="p-3">
              <text class="font-medium text-gray-900">{{ pattern.pattern_name }}</text>
            </view>
          </view>
        </view>
      </view>

        <!-- 空状态 -->
        <view v-else-if="!loading" class="flex flex-col items-center justify-center py-20">
          <view class="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mb-4">
            <text class="fas fa-search text-4xl text-gray-300"></text>
          </view>
          <text class="text-gray-500 mb-2">暂无找到相关图案</text>
          <text class="text-sm text-gray-400">尝试更换分类</text>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore && patterns.length > 0" class="flex justify-center items-center py-6">
          <view v-if="loadingMore" class="flex items-center">
            <text class="fas fa-circle-notch fa-spin mr-2 text-blue-500"></text>
            <text class="text-gray-500">加载中...</text>
          </view>
          <text v-else class="text-blue-500 px-4 py-2 rounded-full bg-blue-50" @click="loadMorePatterns">加载更多</text>
        </view>

        <!-- 没有更多 -->
        <view v-if="!hasMore && patterns.length > 0" class="flex justify-center items-center py-6">
          <text class="text-gray-400 text-sm">没有更多图案了</text>
        </view>
    </scroll-view>
  </view>
</template>

<script>
  import { patternApi, dictApi ,featuredPlaylistApi} from '@/api/index.js'
  
  export default {
  name: 'Explore',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      searchTimeout: null,
      
      // 分类相关
      selectedCategory: 'all',
      categories: [],
      
      // 排序相关
      sortIndex: 0,
      sortOptions: [
        { value: 'popular', name: '最受欢迎' },
        { value: 'newest', name: '最新上传' },
        { value: 'favorite', name: '收藏最多' },
        { value: 'name', name: '名称排序' }
      ],
      
      // 数据相关
      patterns: [],
      featuredPatterns: [],
      featuredPlaylists: [
        // 默认数据，会被API返回的数据替换
        { id: 'nature', title: '自然风景', count: 23, type: 'nature', background: 'linear-gradient(135deg, #2CCCFF, #20B4F9)' },
        { id: 'art', title: '艺术', count: 15, type: 'art', background: 'linear-gradient(135deg, #FF61D2, #BD34FE)' },
        { id: 'abstract', title: '抽象', count: 12, type: 'abstract', background: 'linear-gradient(135deg, #13E2DA, #01A38B)' },
        { id: 'geometry', title: '几何', count: 18, type: 'geometry', background: 'linear-gradient(135deg, #FF9A44, #FC6076)' }
      ],
      totalCount: 0,
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      
      // 状态相关
      loading: false,
      loadingMore: false,
      refreshing: false,
      
      // 用户相关
      userId: null
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  onShow() {
    // 检查登录状态
    const userInfo = uni.getStorageSync('uni-id-pages-userInfo')
    if (userInfo && userInfo._id) {
      this.userId = userInfo._id
      // 页面显示时刷新收藏状态
      this.refreshFavoriteStatus()
    } else {
      this.userId = null
    }
    
    // 如果是首次加载或者数据为空，重新加载数据
    if (this.patterns.length === 0) {
      this.loadPatterns(true)
    }
  },
  
  methods: {
    async initPage() {
      // 获取用户信息
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo')
      if (userInfo && userInfo._id) {
        this.userId = userInfo._id
      }
      
      // 加载数据
      await this.loadCategories()
      await this.loadFeaturedPatterns()
      await this.loadFeaturedPlaylists()
      await this.loadPatterns(true)
    },

    async loadCategories() {
      try {
        // 添加全部分类选项
        const allCategory = { value: 'all', name: '全部', icon: 'th-large' }
        
        // 使用字典API获取图案分类
        const result = await dictApi.getPatternCategories()
        if (result.errCode === 0 && result.data && result.data.length > 0) {
          // 从字典API获取的分类
          const categoryList = result.data.map(cat => ({
            value: cat.value || cat.id,  // 兼容不同的字段名
            name: cat.name || cat.label, // 兼容不同的字段名
            name_en: cat.name_en,
            icon: cat.icon || this.getCategoryIcon(cat.value || cat.id || cat.name || cat.label),
            color: cat.color
          }))
          
          // 如果返回的数据中没有"全部"分类，则添加
          if (!categoryList.some(item => item.value === 'all')) {
            categoryList.unshift(allCategory)
          }
          
          this.categories = categoryList
        } else {
          // 从模式API获取分类（作为备选）
          const backupResult = await patternApi.getCategoryList()
          if (backupResult.errCode === 0 && backupResult.data && backupResult.data.length > 0) {
            const categoryList = backupResult.data.map(cat => ({
              value: cat.id || cat.value || cat.name.toLowerCase(),
              name: cat.name || cat.label,
              icon: cat.icon || this.getCategoryIcon(cat.id || cat.value || cat.name.toLowerCase())
            }))
            
            // 将"全部"添加到列表开头
            this.categories = [allCategory, ...categoryList]
          } else {
            // 使用默认分类
            this.categories = [
              allCategory,
              { value: 'nature', name: '自然', icon: 'leaf' },
              { value: 'animal', name: '动物', icon: 'paw' },
              { value: 'abstract', name: '抽象', icon: 'paint-brush' },
              { value: 'geometry', name: '几何', icon: 'shapes' },
              { value: 'art', name: '艺术', icon: 'palette' },
              { value: 'character', name: '人物', icon: 'user' },
              { value: 'cartoon', name: '卡通', icon: 'smile' },
              { value: 'other', name: '其他', icon: 'ellipsis-h' }
            ]
          }
        }
      } catch (error) {
        console.error('加载分类失败:', error)
        // 使用默认分类
        this.categories = [
          { value: 'all', name: '全部', icon: 'th-large' },
          { value: 'nature', name: '自然', icon: 'leaf' },
          { value: 'animal', name: '动物', icon: 'paw' },
          { value: 'abstract', name: '抽象', icon: 'paint-brush' },
          { value: 'geometry', name: '几何', icon: 'shapes' },
          { value: 'art', name: '艺术', icon: 'palette' },
          { value: 'character', name: '人物', icon: 'user' },
          { value: 'cartoon', name: '卡通', icon: 'smile' },
          { value: 'other', name: '其他', icon: 'ellipsis-h' }
        ]
      }
    },

    async loadFeaturedPatterns() {
      try {
        const result = await patternApi.getFeaturedPatterns(10)
        if (result.errCode === 0) {
          this.featuredPatterns = result.data.map(pattern => this.formatPattern(pattern))
        }
      } catch (error) {
        console.error('加载精选图案失败:', error)
        this.featuredPatterns = []
      }
    },
    
    // 加载热门播放列表
    async loadFeaturedPlaylists() {
      try {
        
        const result = await featuredPlaylistApi.getFeaturedPlaylists({limit: 4});
        if (result.errCode === 0 && result.data) {
          // 确保每个播放列表都有有效的ID
          this.featuredPlaylists = result.data.map(playlist => {
            // 确保ID存在并且是字符串类型
            if (!playlist.id && playlist._id) {
              playlist.id = playlist._id;
            } else if (!playlist.id) {
              // 如果没有ID，生成一个基于类型的ID
              playlist.id = playlist.type || `playlist-${Date.now()}`;
            }
            return playlist;
          });
          console.log('获取热门播放列表成功:', this.featuredPlaylists);
        } else {
          // 保留默认数据作为备用，确保每个项目有一个有效的ID
          console.log('使用默认热门播放列表数据');
        }
      } catch (error) {
        console.error('加载热门播放列表失败:', error);
        // 保留默认数据
      }
    },
    
    // 检查图片URL是否有效并返回修正后的URL
    getValidImageUrl(pattern) {
      // 按优先级检查可用的图片字段
      const possibleFields = [
        'preview_image',
        'thumbnail', 
        'cover_image', 
        'pattern_file'
      ];
      
      // 检查每个可能的字段
      for (const field of possibleFields) {
        if (pattern[field] && typeof pattern[field] === 'string' && pattern[field].trim() !== '') {
          return pattern[field];
        }
      }
      
      // 如果没有找到有效的图片URL，返回默认图片
      return '/static/pattern_images/default.svg';
    },
    
    // 格式化图案数据，统一字段名称
    formatPattern(pattern) {
      const validImageUrl = this.getValidImageUrl(pattern);
      
      return {
        ...pattern,
        patternName: pattern.pattern_name || pattern.name,
        favoriteCount: pattern.favorite_count || 0,
        downloadCount: pattern.download_count || 0,
        thumbnail: validImageUrl,
        preview_image: pattern.preview_image || validImageUrl,
        isFavorite: pattern.isFavorite || false,
        category: pattern.category || pattern.category_id || 'other'
      }
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      // 当图片加载失败时，将其替换为默认图片
      const defaultImage = '/static/pattern_images/default.svg';
      if (e && e.target && e.target.src !== defaultImage) {
        e.target.src = defaultImage;
      }
    },

    async loadPatterns(reset = false) {
      if (this.loading || this.loadingMore) return
      
      if (reset) {
        this.currentPage = 1
        this.patterns = []
        this.hasMore = true
        this.loading = true
      } else {
        this.loadingMore = true
      }

      try {
        const result = await patternApi.getPatternList(
          this.selectedCategory === 'all' ? null : this.selectedCategory,
          this.currentPage,
          this.pageSize,
          this.searchKeyword,
          this.sortOptions[this.sortIndex].value
        )

        if (result.errCode === 0) {
          const newPatterns = result.data.list || []
          
          // 格式化图案数据
          const formattedPatterns = newPatterns.map(pattern => this.formatPattern(pattern))
          
          if (reset) {
            this.patterns = formattedPatterns
          } else {
            this.patterns = [...this.patterns, ...formattedPatterns]
          }
          
          this.totalCount = result.data.total || 0
          this.hasMore = formattedPatterns.length >= this.pageSize && this.patterns.length < this.totalCount
          
          if (this.hasMore) {
            this.currentPage++
          }
          
          // 如果用户已登录，加载收藏状态
          if (this.userId) {
            await this.loadFavoriteStatus()
          }
        }
      } catch (error) {
        console.error('加载图案失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.loadingMore = false
        this.refreshing = false
      }
    },

    async loadFavoriteStatus() {
      if (!this.userId || this.patterns.length === 0) return
      
      try {
        // 获取用户收藏列表
        const result = await patternApi.getUserFavorites(this.userId)
        if (result.errCode === 0) {
          const favoritePatternIds = result.data.patterns ? 
            result.data.patterns.map(p => p._id) : 
            (result.data.list ? result.data.list.map(p => p._id) : [])
          
          // 更新图案收藏状态
          this.patterns.forEach(pattern => {
            pattern.isFavorite = favoritePatternIds.includes(pattern._id)
          })
          
          // 更新精选图案的收藏状态
          if (this.featuredPatterns.length > 0) {
            this.featuredPatterns.forEach(pattern => {
              pattern.isFavorite = favoritePatternIds.includes(pattern._id)
            })
          }
        }
      } catch (error) {
        console.error('加载收藏状态失败:', error)
      }
    },

    async refreshFavoriteStatus() {
      if (this.patterns.length > 0 || this.featuredPatterns.length > 0) {
        await this.loadFavoriteStatus()
      }
    },

    // 搜索相关
    onSearchInput() {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout)
      }
      
      this.searchTimeout = setTimeout(() => {
        this.loadPatterns(true)
      }, 500)
    },

    // 分类选择
    // 选择分类
    selectCategory(categoryValue) {
      if (this.selectedCategory !== categoryValue) {
        this.selectedCategory = categoryValue
        // 重新加载图案列表
        this.loadPatterns(true)
        // 如果分类变更，也需要重新加载推荐内容
        this.loadCategorySpecificContent(categoryValue)
      }
    },

    // 根据选定的分类加载相关推荐内容
    async loadCategorySpecificContent(category) {
      try {
        // 如果是 'all'，加载热门推荐内容
        if (category === 'all') {
          await this.loadFeaturedPatterns()
          return
        }
        
        // 对于其他分类，不需要加载热门推荐内容
        // 为了避免显示旧的推荐内容，清空featuredPatterns数组
        this.featuredPatterns = []
      } catch (error) {
        console.error('加载分类推荐内容失败:', error)
      }
    },

    // 排序变更
    onSortChange(e) {
      this.sortIndex = e.detail.value
      this.loadPatterns(true)
    },

    async onRefresh() {
      this.refreshing = true
      // 刷新播放列表
      await this.loadFeaturedPlaylists()
      // 刷新图案列表
      await this.loadPatterns(true)
      
      // 如果是"全部"类别，才加载热门推荐
      if (this.selectedCategory === 'all') {
        await this.loadFeaturedPatterns()
      } else {
        // 其他分类不显示热门推荐，清空数组
        this.featuredPatterns = []
      }
      
      this.refreshing = false
    },

    // 加载更多
    loadMorePatterns() {
      if (this.hasMore && !this.loadingMore) {
        this.loadPatterns(false)
      }
    },

    // 收藏切换
    async toggleFavorite(pattern) {
      // 如果未登录，跳转到登录页面
      if (!this.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 2000
        });
        
        setTimeout(() => {
          uni.navigateTo({
            url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
          })
        }, 1500);
        return
      }
      
      try {
        // 乐观更新UI
        const originalState = pattern.isFavorite
        pattern.isFavorite = !pattern.isFavorite
        
        // 如果收藏，则增加收藏计数；如果取消收藏，则减少收藏计数
        if (pattern.isFavorite) {
          pattern.favoriteCount = (pattern.favoriteCount || 0) + 1
        } else if (pattern.favoriteCount > 0) {
          pattern.favoriteCount -= 1
        }
        
        // 调用API更新收藏状态
        const action = pattern.isFavorite ? 'add' : 'remove'
        const result = await patternApi.togglePatternFavorite(pattern._id, action)
        
        if (result.errCode !== 0) {
          // 如果API调用失败，恢复之前的状态
          pattern.isFavorite = originalState
          if (originalState) {
            pattern.favoriteCount = (pattern.favoriteCount || 1) - 1
          } else if (pattern.favoriteCount >= 0) {
            pattern.favoriteCount += 1
          }
          
          uni.showToast({
            title: result.errMsg || '操作失败',
            icon: 'none'
          })
        } else {
          // 成功提示
          uni.showToast({
            title: pattern.isFavorite ? '收藏成功' : '取消收藏',
            icon: 'success',
            duration: 1500
          })
        }
      } catch (error) {
        // 如果发生异常，恢复之前的状态
        pattern.isFavorite = !pattern.isFavorite
        
        console.error('切换收藏状态失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },

    // 格式化时长
    formatDuration(seconds) {
      if (!seconds) return '0:00'
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins}:${secs.toString().padStart(2, '0')}`
    },
    
    // 获取分类名称
    getCategoryName(categoryId) {
      // 查找分类名称
      const category = this.categories.find(c => c.value === categoryId)
      if (category) {
        return category.name
      }
      // 如果没有找到匹配的分类，返回分类ID或默认文本
      return categoryId || '未分类'
    },
    
    // 获取分类图标
    getCategoryIcon(category) {
      // 基于分类名称或ID返回合适的图标
      const iconMap = {
        'all': 'th-large',
        'nature': 'leaf',
        'animal': 'paw',
        'abstract': 'paint-brush',
        'geometry': 'shapes',
        'art': 'palette',
        'character': 'user',
        'cartoon': 'smile',
        'landscape': 'mountain',
        'plant': 'seedling',
        'building': 'building',
        'vehicle': 'car',
        'food': 'utensils',
        'other': 'ellipsis-h'
      }
      
      // 尝试从映射中获取图标
      if (category && typeof category === 'string') {
        const lowerCategory = category.toLowerCase()
        // 精确匹配
        if (iconMap[lowerCategory]) {
          return iconMap[lowerCategory]
        }
        
        // 模糊匹配
        for (const [key, icon] of Object.entries(iconMap)) {
          if (lowerCategory.includes(key)) {
            return icon
          }
        }
      }
      
      // 默认图标
      return 'tag'
    },

    // 页面跳转
    goToPatternDetail(patternId) {
  
      uni.navigateTo({
        url: `/pages/pattern/detail?id=${patternId}`
      })
    },
    
    // 播放列表跳转
    goToPlaylist(playlistId) {
      // 确保playlistId是一个有效的字符串或数字
      if (!playlistId || (typeof playlistId !== 'string' && typeof playlistId !== 'number')) {
        console.error('无效的播放列表ID:', playlistId);
        uni.showToast({
          title: '无效的播放列表ID',
          icon: 'none'
        });
        return;
      }
      
      // 转换为字符串确保API调用正确
      const id = String(playlistId);
      
      console.log('正在获取播放列表详情, ID:', id);
            
      // 直接跳转到播放列表详情页
      uni.navigateTo({
        url: `/pages/explore/detail?id=${id}`
      });
    },

    viewAllFeatured() {
      // 将当前分类设置为 'all'，并应用精选过滤器
      this.selectedCategory = 'all'
      this.searchKeyword = ''
      this.sortIndex = 0 // 恢复到默认排序
      
      // 提示用户
      uni.showToast({
        title: '正在加载精选内容',
        icon: 'none'
      })
      
      // 加载数据
      this.loadPatterns(true)
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 样式类 */
.bg-white { background-color: #ffffff; }
.bg-gray-50 { background-color: #f9fafb; }
.bg-gray-100 { background-color: #f3f4f6; }
.bg-blue-50 { background-color: #eff6ff; }
.bg-blue-500 { background-color: #3b82f6; }

.text-white { color: #ffffff; }
.text-gray-300 { color: #d1d5db; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-gray-700 { color: #374151; }
.text-gray-900 { color: #111827; }
.text-blue-500 { color: #3b82f6; }
.text-blue-600 { color: #2563eb; }
.text-red-400 { color: #f87171; }
.text-red-500 { color: #ef4444; }
.text-yellow-500 { color: #eab308; }

.text-xs { font-size: 24rpx; }
.text-sm { font-size: 28rpx; }
.text-lg { font-size: 36rpx; }
.text-xl { font-size: 40rpx; }
.text-4xl { font-size: 72rpx; }

.font-bold { font-weight: 700; }
.font-medium { font-weight: 500; }

.h-screen { height: 100vh; }
.h-8 { height: 64rpx; }
.h-40 { height: 320rpx; }
.w-8 { width: 64rpx; }
.w-40 { width: 320rpx; }
.w-48 { width: 384rpx; }
.w-full { width: 100%; }

.px-2 { padding-left: 16rpx; padding-right: 16rpx; }
.px-3 { padding-left: 24rpx; padding-right: 24rpx; }
.px-4 { padding-left: 32rpx; padding-right: 32rpx; }
.px-6 { padding-left: 48rpx; padding-right: 48rpx; }
.py-1 { padding-top: 8rpx; padding-bottom: 8rpx; }
.py-2 { padding-top: 16rpx; padding-bottom: 16rpx; }
.py-4 { padding-top: 32rpx; padding-bottom: 32rpx; }
.py-20 { padding-top: 160rpx; padding-bottom: 160rpx; }
.pt-12 { padding-top: 96rpx; }
.pb-2 { padding-bottom: 16rpx; }
.pb-4 { padding-bottom: 32rpx; }
.p-3 { padding: 24rpx; }

.mb-1 { margin-bottom: 8rpx; }
.mb-2 { margin-bottom: 16rpx; }
.mb-4 { margin-bottom: 32rpx; }
.mb-6 { margin-bottom: 48rpx; }
.mb-8 { margin-bottom: 64rpx; }
.mr-1 { margin-right: 8rpx; }
.mr-2 { margin-right: 16rpx; }
.ml-2 { margin-left: 16rpx; }
.mt-1 { margin-top: 8rpx; }
.mt-2 { margin-top: 16rpx; }

.flex { display: flex; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }
.flex-shrink-0 { flex-shrink: 0; }
.flex-wrap { flex-wrap: wrap; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }
.justify-end { justify-content: flex-end; }

.space-x-2 > * + * { margin-left: 16rpx; }
.space-x-3 > * + * { margin-left: 24rpx; }
.space-x-4 > * + * { margin-left: 32rpx; }

.grid { display: grid; }
.grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.gap-4 { gap: 32rpx; }

.rounded-full { border-radius: 50%; }
.rounded-xl { border-radius: 24rpx; }
.rounded-3xl { border-radius: 24rpx; }
.rounded-t-3xl { border-radius: 24rpx 24rpx 0 0; }
.rounded-b-3xl { border-radius: 0 0 24rpx 24rpx; }
.rounded { border-radius: 8rpx; }

.border { border-width: 1px; }
.border-gray-100 { border-color: #f3f4f6; }

.shadow-sm { box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); }
.shadow-md { box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }

.overflow-auto { overflow: auto; }
.overflow-x-auto { overflow-x: auto; }
.overflow-hidden { overflow: hidden; }

.relative { position: relative; }
.absolute { position: absolute; }
.top-2 { top: 16rpx; }
.right-2 { right: 16rpx; }
.right-3 { right: 24rpx; }
.bottom-2 { bottom: 16rpx; }
.left-2 { left: 16rpx; }
.inset-0 { top: 0; right: 0; bottom: 0; left: 0; }

.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.whitespace-nowrap { white-space: nowrap; }
.block { display: block; }

.object-cover { object-fit: cover; }
.aspect-square { aspect-ratio: 1; }

.transition-all { transition-property: all; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; }

.focus\:bg-white:focus { background-color: #ffffff; }
.focus\:shadow-md:focus { box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }

/* 自定义样式 */
.category-btn {
  transition: all 0.2s ease;
}

.bg-gradient-to-t {
  background: linear-gradient(to top, var(--tw-gradient-stops));
}

.from-black\/50 {
  --tw-gradient-from: rgba(0, 0, 0, 0.5);
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(0, 0, 0, 0));
}

.to-transparent {
  --tw-gradient-to: transparent;
}

.bg-blue-500\/70 {
  background-color: rgba(59, 130, 246, 0.7);
}

.category-tag {
  backdrop-filter: blur(4px);
}

.pattern-card {
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.pattern-card:active {
  transform: scale(0.98);
}

.shadow-sm {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

.border {
  border-width: 1px;
}

.border-gray-200 {
  border-color: #e5e7eb;
}

.rounded-lg {
  border-radius: 0.5rem;
}

.aspect-square {
  aspect-ratio: 1;
}

.pattern-image-container {
  /* 图片保持1:1的正方形比例 */
  aspect-ratio: 1;
  width: 100%;
  height: 0;
  padding-bottom: 100%;
  position: relative;
}

/* 确保图片容器保持正方形 */
.pattern-image-wrapper {
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* 创建一个正方形的容器 */
  height: 0;
  overflow: hidden;
}

/* 确保图片填充整个容器并保持比例 */
.pattern-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.object-cover {
  object-fit: cover;
}

/* 覆盖uni-image的固定高度设置 */
uni-image {
  height: auto !important;
  width: 100% !important;
}

image {
  height: 100% !important;
  width: 100% !important;
}

.font-medium {
  font-weight: 500;
}

.text-gray-900 {
  color: #111827;
}

.category-tabs::-webkit-scrollbar {
  display: none;
}

/* 分类标签样式 - 水平排列固定在顶部 */
.category-container {
  width: 100%;
  background-color: #fff;
  z-index: 10;
  position: sticky;
  top: 0;
  padding: 20px 10px;
}

.category-scroll {
  width: 100%;
  white-space: nowrap;
}

.category-row {
  display: flex;
  flex-direction: row;
  padding: 0 15px 10px 0;
}

.category-item {
  min-width: auto;
  height: 36px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  margin-right: 10px;
  border-radius: 18px;
  position: relative;
  overflow: hidden;
  padding: 0 20px;
  flex-shrink: 0;
}

.category-text {
  font-size: 14px;
  color: #333;
  z-index: 1;
  white-space: nowrap;
}

.category-active {
  background-color: transparent;
}

.category-active .category-text {
  color: white;
}

.category-active::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #4080ff;
  border-radius: 18px;
  z-index: 0;
}

.featured-playlist-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 0 2px;
}

.featured-playlist {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border-radius: 16px;
  overflow: hidden;
}

.playlist-card-content {
  /* 播放列表卡片内容也保持1:1的正方形比例 */
  aspect-ratio: 1;
  width: 100%;
  height: 0;
  padding-bottom: 66.67%;
  position: relative;
}

/* 确保播放列表图片包装器保持正方形 */
.playlist-image-wrapper {
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* 创建一个正方形的容器 */
  height: 0 !important;
  overflow: hidden;
}

.featured-playlist:active {
  transform: scale(0.98);
}

.play-btn-circle {
  width: 42px;
  height: 42px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  margin-right: 8px;
  margin-bottom: 8px;
}

.play-icon {
  font-size: 16px;
}

.play-btn-circle:active {
  transform: scale(0.9);
  background-color: rgba(255, 255, 255, 0.5);
}

.text-content {
  margin-left: 10px;
  margin-top: 20px;
}

/* 渐变背景 - 匹配截图中的设计 */
.gradient-romantic {
  background: linear-gradient(135deg, #C93C8B, #9A2ACE);
}

.gradient-nature {
  background: linear-gradient(135deg, #36B9F7, #3F7EF7);
}

.gradient-creative {
  background: linear-gradient(135deg, #21C093, #14AE7E);
}

.gradient-geometric {
  background: linear-gradient(135deg, #FF9740, #FF8E2E);
}

/* 圆角 */
.rounded-3xl {
  border-radius: 1.5rem;
}

.rounded-2xl {
  border-radius: 1rem;
}
</style>
